package com.example.myblog.service;

import com.example.myblog.NotFoundException;
import com.example.myblog.dao.TypeDao;
import com.example.myblog.entity.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;


import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by asus on 2020/5/28 21:21
 */
@Service
public class TypeService{

    @Autowired TypeDao typeDao;

    //增加分类
    @Transactional
    public Type saveType(Type type)
    {
        return typeDao.save(type);
    }

    //根据ID查
    @Transactional
    public Type getType(Long id){
        return typeDao.getOne(id);
    }

    //分页查询显示
    @Transactional
    public Page<Type> listType(Pageable pageable){
        return typeDao.findAll(pageable);
    }

    //查所有的分类
    public List<Type> listType(){
        return typeDao.findAll();
    }

    //更新分类，先查ID再更新，也可以直接save
    @Transactional
    public Type updateType(Long id,Type type){
        Type t = typeDao.getOne(id);
        if(t == null){
            throw new NotFoundException("Id不存在");
        }
        //把type中的值赋给t
        BeanUtils.copyProperties(type,t);
        return typeDao.save(t);
    }

    @Transactional
    public List<Type> ListTypeTop(Integer size){
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return typeDao.findTop(pageable);
    }

    //根据ID删除
    @Transactional
    public void deleteType(Long id){
        typeDao.deleteById(id);
    }

    //获取类型名字
    @Transactional
    public Type getTypeName(String name){
        return typeDao.findByName(name);
    }
}
